package common.tool.box.common.utils.treeNode;

import java.util.*;

public class TreeUtils {
    /**
     * 根据组织id和组织树列表获取以id为根的组织树
     * @author jiazekai 2022/10/11
     * @param topId, entityList
     * @return java.util.List<T>
     */
    public static <T extends DeptTreeInterface<T>> List<T> getTreeList(Long topId, List<T> entityList) {
        topId = Optional.ofNullable(topId).orElse(0L);
        List<T> resultList = new ArrayList<>();//存储顶层的数据

        Map<Object, T> treeMap = new HashMap<>();
        T itemTree;

        for (int i = 0; i < entityList.size() && !entityList.isEmpty(); i++) {
            itemTree = entityList.get(i);
            treeMap.put(itemTree.getDeptId(), itemTree);//把所有的数据放到map当中，id为key
            if (topId.equals(itemTree.getParentId())) {//把顶层数据放到集合中
                resultList.add(itemTree);
            }
        }

        //循环数据，把数据放到上一级的childen属性中
        for (int i = 0; i < entityList.size() && !entityList.isEmpty(); i++) {
            itemTree = entityList.get(i);
            T data = treeMap.get(itemTree.getParentId());//在map集合中寻找父亲
            if (data != null) {//判断父亲有没有
                if (data.getChildren() == null) {
                    data.setChildren(new ArrayList<>());
                }
                data.getChildren().add(itemTree);//把子节点 放到父节点childList当中
                treeMap.put(itemTree.getParentId(), data);//把放好的数据放回map当中
            }
        }
        return resultList;
    }
}
